/**
 * Created by SN on 2017/5/22.
 */
// 使用 Web Audio API
const AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext;

let getSource = () => ({
  start: function () {
  }
});

function load(url, fn) {
  if (!AudioContext) return;
  fetch(url).then(response => response.arrayBuffer()).then(buffer => {

    const audioCtx = new AudioContext();
    audioCtx.decodeAudioData(buffer, decodedData => {
      fn(() => {
        let source = audioCtx.createBufferSource();
        source.buffer = decodedData;
        source.connect(audioCtx.destination);
        return source
      });
    });

  }).catch(err => console.log(err));
}

export function play(url, when, offset, duration) {
  load(url, fn => {
    fn().start(when, offset, duration);
  });
}

export function source(url, done) {
  load(url, fn => {
    getSource = fn;
    done();
  });
}

export function start(when, offset, duration) {
  let source = getSource();
  source.start(when, offset, duration);
  return source;
}
